<template>
	<view class="container">
		<cu-custom bgColor="bg-gradual-blue" :isBack="true">
			<block slot="backText"></block>
			<block slot="content">商户编辑</block>
		</cu-custom>

		<view class="margin-top" style="background-color: white; padding-left: 40rpx; padding-right: 40rpx;">
			<u--form
				labelPosition="left"
				labelWidth="80"
				:model="formData"
				:rules="rules"
				ref="uForm"
			>
				<u-form-item
					label="商户名称"
					labelWidth="80"
					prop="name"
					borderBottom
				>
					<u-input
						v-model="formData.name"
						border="none"
						placeholder="请输入商户名称"
					>
					</u-input>
				</u-form-item>
				<u-form-item
					label="商户规模"
					labelWidth="80"
					prop="shopScale"
					borderBottom
					@click="showScale = true;"
				>
					<u--text :text="formData.shopScaleText"></u--text>
					<u-icon
							slot="right"
							name="arrow-right"
					></u-icon>
				</u-form-item>
				<u-form-item
					label="营业执照"
					labelWidth="80"
					prop="licenseNumber"
					borderBottom
				>
					<u-input
						v-model="formData.licenseNumber"
						border="none"
						placeholder="请输入营业执照"
					>
					</u-input>
				</u-form-item>
				<u-form-item
					label="执照名称"
					labelWidth="80"
					prop="licenseName"
					borderBottom
				>
					<u-input
						v-model="formData.licenseName"
						border="none"
						placeholder="请输入执照名称"
					>
					</u-input>
				</u-form-item>
				<u-form-item
					label="行业"
					labelWidth="80"
					prop="industry"
					borderBottom
					@click="showIndustry = true;"
				>
					<u--text :text="formData.industryText"></u--text>
					<u-icon
							slot="right"
							name="arrow-right"
					></u-icon>
				</u-form-item>
				<u-form-item
					label="省市区"
					labelWidth="80"
					prop="city"
					borderBottom
					@click="showCity = true;"
				>
					<u--text size="14" :text="formData.provinceText + formData.cityText + formData.areaText + formData.townText"></u--text>
					<u-icon
							slot="right"
							name="arrow-right"
					></u-icon>
				</u-form-item>
				<u-form-item
					label="详细地址"
					labelWidth="80"
					prop="address"
					borderBottom
				>
					<u-input
						v-model="formData.address"
						border="none"
						placeholder="请输入详细地址"
					>
					</u-input>
				</u-form-item>
				<u-form-item
					label="商户定位"
					labelWidth="80"
					prop="longitudeGcj02"
					borderBottom
					@click="toLocation"
				>
					<u-input
						v-model="formData.longitudeGcj02"
						border="none"
						disabled
						disabledColor="#ffffff"
						placeholder="请选择地图定位"
					>
					</u-input>
					<u-icon
							slot="right"
							name="arrow-right"
					></u-icon>
				</u-form-item>
				<u-form-item
					label="联系人"
					labelWidth="80"
					prop="contact"
					borderBottom
				>
					<u-input
						v-model="formData.contact"
						border="none"
						placeholder="请输入联系人"
					>
					</u-input>
				</u-form-item>
				<u-form-item
					label="联系号码"
					labelWidth="80"
					prop="mobile"
					borderBottom
				>
					<u-input
						v-model="formData.mobile"
						border="none"
						placeholder="请输入联系号码"
					>
					</u-input>
				</u-form-item>
				<u-form-item
				    v-if="merchant.orgCode == 'A05'"
					label="隔油池清捞单位"
					labelWidth="80"
					prop="shouyunCompany"
					borderBottom
					@click="showSYCompany = true;"
				>
					<u--text :text="formData.shouyunCompanyText"></u--text>
					<u-icon
							slot="right"
							name="arrow-right"
					></u-icon>
				</u-form-item>
				<u-form-item
					label="备注"
					labelWidth="80"
					prop="remark"
					borderBottom
				>
					<u-input
						v-model="formData.remark"
						border="none"
						placeholder="请输入备注"
					>
					</u-input>
				</u-form-item>
				<u-form-item
					label="状态"
					labelWidth="80"
					prop="status"
					borderBottom
					@click="showStatus = true;"
				>
					<u--text :text="formData.statusText"></u--text>
					<u-icon
							slot="right"
							name="arrow-right"
					></u-icon>
				</u-form-item>
			</u--form>
			<u-gap height="30" bgColor="#fff"></u-gap>
			<u-button text="提交" type="primary" @click="submitForm"></u-button>
			<u-gap height="20" bgColor="#fff"></u-gap>
			<view>
				<u-radio-group v-model="protocol">
					<u-radio shape="circle" label="同意" labelSize="12" name="agree"></u-radio>
					<u--text decoration="underline" text="用户服务及隐私协议" size="13" @click="clickProtocol" type="primary"></u--text>
				</u-radio-group>
			</view>
			<u-gap height="30" bgColor="#fff"></u-gap>
		</view>
		
		<u-picker :show="showIndustry" title="选择行业" :columns="industryColumns" :defaultIndex="selectedIndustryIndex" keyName="label" :closeOnClickOverlay="true" @confirm="changeIndustry" @close="cancelIndustry" @cancel="cancelIndustry"></u-picker>
		<u-picker :show="showStatus" title="选择状态" :columns="statusColumns" :defaultIndex="selectedStatusIndex" keyName="label" :closeOnClickOverlay="true" @confirm="changeStatus" @close="cancelStatus" @cancel="cancelStatus"></u-picker>
		<u-picker :show="showCity" ref="cityPicker" :defaultIndex="selectedCityIndex" title="浙江省" :loading="loadingCity" keyName="label" :columns="columnsCity" @change="changeCity" @confirm="closeCity" @close="closeCity" @cancel="closeCity" :closeOnClickOverlay="true"></u-picker>
		<u-picker :show="showScale" title="选择商户规模" :columns="scaleColumns" :defaultIndex="selectedScaleIndex" keyName="label" :closeOnClickOverlay="true" @confirm="changeScale" @close="cancelScale" @cancel="cancelScale"></u-picker>
		<u-picker :show="showSYCompany" title="选择隔油池清捞单位" :columns="shouyunCompanyColumns" :defaultIndex="selectedShouyunCompanyIndex" keyName="label" :closeOnClickOverlay="true" @confirm="changeSYCompany" @close="cancelSYCompany" @cancel="cancelSYCompany"></u-picker>
		<u-popup :show="showProtocol" :closeOnClickOverlay="true" @close="showProtocol = false;">
			<view class="padding">
				<u--text text="用户服务及隐私协议" color="#333333" :bold="true" size="16" align="center"></u--text>
				<u-gap height="10" bgColor="#fff"></u-gap>
				<u--text size="14" lineHeight="30" text="我们致力于保护您在使用我们小程序时所提供的私隐、私人资料以及个人的资料(统称“个人资料”)，使我们在收集、使用、储存和传送个人资料方面符合(与个人资料私隐有关的法律法规)及消费者保护方面的最高标准。 为确保您对我们在处理个人资料上有充分信心，您切要详细阅读及理解隐私政策的条文。"></u--text>
				<u-gap height="8" bgColor="#fff"></u-gap>
				<u--text size="14" lineHeight="30" text="收集个人资料的目的及用途如下:通过我们的小程序向您提供我们的各项服务;当您使用我们的小程序时，能辨认以及确认您的身份;您上报的油烟及隔油池信息将绑定到您填写的商户名下,以便后续与我们结算各项事宜。"></u--text>
				<u-gap height="8" bgColor="#fff"></u-gap>
				<u--text size="14" lineHeight="30" text="感谢您的阅读,我们将竭诚为您服务。"></u--text>
				<u-gap height="15" bgColor="#fff"></u-gap>
			</view>
		</u-popup>
		<!-- 加载弹窗 -->
		<view class="cu-load load-modal" v-if="loading">
			<!-- <view class="cuIcon-emojifill text-orange"></view> -->
			<image src="https://mini.wm-mis.com/img/static/car.png" mode="aspectFit" class="round"></image>
			<view class="gray-text">加载中...</view>
		</view>
	</view>
</template>

<script>
	import api from '@/api/api'
	import {
		mapState
	} from 'vuex';
	
	export default {
		computed: {
			...mapState([
				'merchant',
				'dicts'
			])
		},
		data() {
			return {
				param: null,
				merchantDetail: null,
				id: null,
				loading: false,
				showIndustry: false,
				industryColumns: [],
				selectedIndustryIndex: [0],
				showStatus: false,
				statusColumns: [],
				selectedStatusIndex: [0],
				loadingCity: false,
				showCity: false,
				columnsCity: [],
				selectedCityIndex: [0, 0, 0],
				showScale: false,
				scaleColumns: [],
				selectedScaleIndex: [0],
				showSYCompany: false,
				shouyunCompanyColumns: [],
				selectedShouyunCompanyIndex: [0],
				protocol: "agree",
				showProtocol: false,
				formData: {
					id: '',
					name: '',          //商户名称
					shopScale: '',     //商户规模
					shopScaleText: '', 
					shouyunCompany: '',
					shouyunCompanyText: '',
					licenseNumber: '', //执照号码
					licenseName: '',   //执照名称
					mobile: '',        //联系号码
					longitudeGcj02: '',//经度
					latitudeGcj02: '', //纬度
					address: '',       //详细地址
					contact: '',       //联系人
					remark: '',        //备注
					industryText: '',
					industry: '',
					statusText: '',
					status: '',
					province: '33',
					provinceText: '浙江省',
					city: '',
					cityText: '',
					area: '',
					areaText: '',
					town: '',
					townText: '',
				},
				rules: {
					'name': {
						type: 'string',
						required: true,
						message: '请输入商户名称',
						trigger: ['blur', 'change']
					},
					'licenseNumber': {
						type: 'string',
						required: true,
						message: '请输入执照号码',
						trigger: ['blur', 'change']
					},
					'mobile': {
						type: 'string',
						required: true,
						message: '请输入联系号码',
						trigger: ['blur', 'change']
					},
					'contact': {
						type: 'string',
						required: true,
						message: '请输入联系人',
						trigger: ['blur', 'change']
					},
				}
			}
		},
		async onLoad(options){
			this.industryColumns = [this.dicts.industry]
			this.statusColumns = [this.dicts.shop_status]
			this.scaleColumns = [this.dicts.shop_scale]
			this.shouyunCompanyColumns = [this.dicts.shouyun_company]
			
			if(options.item){
				this.param = JSON.parse(options.item)
				this.id = this.param.id
			}
			if(this.id){
				await this.getMerchantDetail();
				let index = 0
				for(let item of this.dicts.industry){
					if(this.formData.industry == item.value){
						this.selectedIndustryIndex = [index]
						this.formData.industryText = item.label
						break
					}
					index++
				}
				
				let index2 = 0
				for(let item of this.dicts.shop_status){
					if(this.formData.status == item.value){
						this.selectedStatusIndex = [index2]
						this.formData.statusText = item.label
						break
					}
					index2++
				}
				
				let index3 = 0
				for(let item of this.dicts.shop_scale){
					if(this.formData.shopScale == item.value){
						this.selectedScaleIndex = [index3]
						this.formData.shopScaleText = item.label
						break
					}
					index3++
				}
				
				let index4 = 0
				for(let item of this.dicts.shouyun_company){
					if(this.formData.shouyunCompany == item.value){
						this.selectedShouyunCompanyIndex = [index4]
						this.formData.shouyunCompanyText = item.label
						break
					}
					index4++
				}
			}
			else{
				//初始化
				this.formData.industry = this.dicts.industry[0].value
				this.formData.industryText = this.dicts.industry[0].label
				this.formData.status = this.dicts.shop_status[0].value
				this.formData.statusText = this.dicts.shop_status[0].label
				this.formData.shopScale = this.dicts.shop_scale[0].value
				this.formData.shopScaleText = this.dicts.shop_scale[0].label
				this.formData.shouyunCompany = this.dicts.shouyun_company[0].value
				this.formData.shouyunCompanyText = this.dicts.shouyun_company[0].label
			}
			
			await this.getCityList('city', '33') //获取浙江省的所有市
		},
		methods: {
			async submitForm(){
				let that = this
				that.loading = true
				let res = null
				let temp = JSON.parse(JSON.stringify(this.formData))
				if(that.merchant.orgCode != 'A05'){
					temp.shouyunCompany = ""
					temp.shouyunCompanyText = ""
				}
				
				if(temp.id){
					res = await api.shopEdit(temp)
				}
				else{
					delete temp.id
					res = await api.shopInsert(temp)
				}
				if(res.data.code == 200 && res.data.success){
					uni.setStorageSync('entryDetail', 'merchantDetail')//添加操作标记，返回时需要刷新
					uni.showToast({
						title: '操作成功',
						icon: 'success',
						duration: 2000
					})
					
					that.loading = false
					setTimeout(()=>{
						uni.navigateBack();
					}, 2000)
				}
				that.loading = false
			},
			async getMerchantDetail(){
				let that = this
				that.loading = true
				let res = await api.shopDetailNoAuth({
					id: that.id
				})
				if(res.data.code == 200 && res.data.success){
					that.merchantDetail = res.data.result
					that.formData = res.data.result
					that.formData.shopScaleText = that.formData.shopScaleText ? that.formData.shopScaleText : ''
					that.formData.industryText = that.formData.industryText ? that.formData.industryText : ''
					that.formData.licenseNumber = that.formData.licenseNumber ? that.formData.licenseNumber : ''
					that.formData.licenseName = that.formData.licenseName ? that.formData.licenseName : ''
					that.formData.mobile = that.formData.mobile ? that.formData.mobile : ''
					that.formData.contact = that.formData.contact ? that.formData.contact : ''
					that.formData.provinceText = that.formData.provinceText ? that.formData.provinceText : '浙江省'
					that.formData.province = that.formData.province ? that.formData.province : '33'
					that.formData.name = that.formData.name ? that.formData.name : ''
					that.formData.remark = that.formData.remark ? that.formData.remark : ''
					that.formData.address = that.formData.address ? that.formData.address : ''
					that.formData.statusText = that.formData.statusText ? that.formData.statusText : ''
					that.formData.shouyunCompanyText = that.formData.shouyunCompanyText ? that.formData.shouyunCompanyText : ''
				}
				that.loading = false
			},
			async changeIndustry(e) {
				const {
					indexs,
					value
				} = e
			
				let that = this;
				that.showIndustry = false;
				
				//选中的设备
				let selectIndex = indexs[0];
				let selectIndustry = that.dicts.industry[selectIndex];
				that.selectedIndustryIndex = [selectIndex];
				that.formData.industry = selectIndustry.value
				that.formData.industryText = selectIndustry.label
			},
			cancelIndustry() {
				this.showIndustry = false;
			},
			async changeStatus(e) {
				const {
					indexs,
					value
				} = e
			
				let that = this;
				that.showStatus = false;
				
				//选中的设备
				let selectIndex = indexs[0];
				let selectStatus = that.dicts.shop_status[selectIndex];
				that.selectedStatusIndex = [selectIndex];
				that.formData.status = selectStatus.value
				that.formData.statusText = selectStatus.label
			},
			cancelStatus() {
				this.showStatus = false;
			},
			toLocation(){
				let that = this
				uni.chooseLocation({
					success: res => {
						console.log('位置名称：' + res.name);
						console.log('详细地址：' + res.address);
						console.log('纬度：' + res.latitude);
						console.log('经度：' + res.longitude);
						that.formData.longitudeGcj02 = res.longitude
						that.formData.latitudeGcj02 = res.latitude
					}
				});
			},
			async getCityList(type, pid){
				let that = this
				that.loadingCity = true
				let res = await api.getCityDistrict({
					pageNo: 1,
					pageSize: 9999,
					pid: pid
				})
				if(res.data.code == 200 && res.data.success){
					if(type == 'city'){
						let cityList = res.data.result.records
						let cityColumn = []
						for(let item of cityList){
							cityColumn.push({
								label: item.qymc,
								value: item.id
							})
						}
						that.columnsCity[0] = cityColumn
						
						//有值时
						let index = 0 //选中的索引
						let flag = false //是否匹配到
						if(that.formData.city){
							for(let item of cityList){
								if(that.formData.city == item.id){
									flag = true
									break
								}
								index++
							}
						}
						else{
							//金华市
							if(that.merchant.orgCode == 'A05' || that.merchant.orgCode == 'A24'){
								for(let item of cityList){
									if(item.qymc == "金华市"){
										flag = true
										break
									}
									index++
								}
							}
						}
						
						let selectedIndex = flag ? index : 0
						await that.getCityList('area', cityColumn[selectedIndex].value) //获取默认市所在区
						that.formData.city = cityList[selectedIndex].id
						that.formData.cityText = cityList[selectedIndex].qymc
						that.selectedCityIndex[0] = selectedIndex
					}
					else if(type == 'area'){
						let areaList = res.data.result.records
						let areaColumn = []
						for(let item of areaList){
							if(item.qymc == '市辖区'){
								continue
							}
							areaColumn.push({
								label: item.qymc,
								value: item.id
							})
						}
						that.columnsCity[1] = areaColumn
						that.$refs.cityPicker.setColumnValues(1, areaColumn)
						
						//有值时
						let index = 0 //选中的索引
						let flag = false //是否匹配到
						if(that.formData.area){
							for(let item of areaList){
								if(that.formData.area == item.id){
									flag = true
									break
								}
								index++
							}
						}
						else{
							//东阳市
							if(that.merchant.orgCode == 'A05'){
								for(let item of areaList){
									if(item.qymc == "东阳市"){
										flag = true
										break
									}
									index++
								}
							}
							else if(that.merchant.orgCode == 'A24'){
								for(let item of areaList){
									if(item.qymc == "永康市"){
										flag = true
										break
									}
									index++
								}
							}
						}
						
						let selectedIndex = flag ? index : 0
						await that.getCityList('town', areaColumn[selectedIndex].value) //获取默认市所在区
						that.formData.area = areaList[selectedIndex].id
						that.formData.areaText = areaList[selectedIndex].qymc
						that.selectedCityIndex[1] = selectedIndex
					}
					else{
						let townList = res.data.result.records
						let townColumn = []
						for(let item of townList){
							townColumn.push({
								label: item.qymc,
								value: item.id
							})
						}
						that.columnsCity[2] = townColumn
						that.$refs.cityPicker.setColumnValues(2, townColumn)
						
						//有值时
						let index = 0 //选中的索引
						let flag = false //是否匹配到
						if(that.formData.town){
							for(let item of townList){
								if(that.formData.town == item.id){
									flag = true
									break
								}
								index++
							}
						}
						
						let selectedIndex = flag ? index : 0
						
						that.formData.town = townList[selectedIndex].id
						that.formData.townText = townList[selectedIndex].qymc
						that.selectedCityIndex[2] = selectedIndex
					}
				}
				that.loadingCity = false
			},
			changeCity(e){
				const {
					columnIndex,
					index,
					// 微信小程序无法将picker实例传出来，只能通过ref操作
					picker = this.$refs.cityPicker
				} = e
				
				// 当第一列值发生变化时，变化第二列(后一列)对应的选项
				if (columnIndex === 0) {
					this.getCityList('area', this.columnsCity[0][index].value)
					this.formData.city = this.columnsCity[0][index].value
					this.formData.cityText = this.columnsCity[0][index].label
				}
				// 当第二列值发生变化时，变化第三列(后一列)对应的选项
				else if (columnIndex === 1) {
					this.getCityList('town', this.columnsCity[1][index].value)
					this.formData.area = this.columnsCity[1][index].value
					this.formData.areaText = this.columnsCity[1][index].label
				}
				else{
					this.formData.town = this.columnsCity[2][index].value
					this.formData.townText = this.columnsCity[2][index].label
				}
			},
			closeCity() {
				this.showCity = false;
			},
			async changeScale(e) {
				const {
					indexs,
					value
				} = e
			
				let that = this;
				that.showScale = false;
				
				//选中的设备
				let selectIndex = indexs[0];
				let selectScale = that.dicts.shop_scale[selectIndex];
				that.selectedScaleIndex = [selectIndex];
				that.formData.shopScale = selectScale.value
				that.formData.shopScaleText = selectScale.label
			},
			cancelScale() {
				this.showScale = false;
			},
			async changeSYCompany(e) {
				const {
					indexs,
					value
				} = e
			
				let that = this;
				that.showSYCompany = false;
				
				//选中的设备
				let selectIndex = indexs[0];
				let selectSYCompany = that.dicts.shouyun_company[selectIndex];
				that.selectedShouyunCompanyIndex = [selectIndex];
				that.formData.shouyunCompany = selectSYCompany.value
				that.formData.shouyunCompanyText = selectSYCompany.label
			},
			cancelSYCompany() {
				this.showSYCompany = false;
			},
			clickProtocol(){
				this.showProtocol = !this.showProtocol
			}
		}
	}
</script>
<style lang="scss" scoped>
	
</style>
